package com.eee.machine.concurrent;

import com.eee.machine.common.OrderItem;

import java.util.LinkedList;
import java.util.List;
import java.util.concurrent.ConcurrentHashMap;

public class OrderHashMap {

//    public final static ConcurrentHashMap orderMap = new ConcurrentHashMap<String, LinkedList>();
    private final ConcurrentHashMap orderMap = new ConcurrentHashMap<String, LinkedList<LinkedList<OrderItem>>>();
    private static volatile OrderHashMap singleton = null;
    private OrderHashMap(){}

    public static OrderHashMap getSingleton() {
        if (singleton == null) {
            synchronized (OrderHashMap.class) {
                if (singleton == null) {
                    singleton = new OrderHashMap();
                }
            }
        }
        return singleton;
    }

    /**
     * 添加订单
     * @param machineId
     * @param orderList
     */
    public void addOrderItem(String machineId, LinkedList<OrderItem> orderList){
        if(orderMap.containsKey(machineId)){
            LinkedList itemList = (LinkedList)orderMap.get(machineId);
            itemList.add(orderList);
        }else{
            LinkedList itemList = new LinkedList<LinkedList<OrderItem>>();
            itemList.add(orderList);
            orderMap.put(machineId, itemList);
        }
    }


    public boolean isExist(String machineId){
        return orderMap.containsKey(machineId);
    }

    public LinkedList getOrder(String machineId){
        boolean exist = isExist(machineId);
        if(exist){
            return (LinkedList)orderMap.get(machineId);
        }else{
            return null;
        }
    }

    /**
     * 获取第一个订单
     * @param machineId
     * @return
     */
    public LinkedList<OrderItem> getOrderItem(String machineId){
        LinkedList order = getOrder(machineId);
        if(order == null){
            return null;
        }else{
            if(order.size() < 1){
                return null;
            }else{
                return (LinkedList) order.removeFirst();
            }
        }
    }

    public int itemSize(){
        return orderMap.size();
    }

}
